﻿using System.IO;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using GitNet.WindowsApp.ViewModels;
using LibGit2Sharp;

namespace GitNet.WindowsApp.AddViews;

public partial class CreateFolderView : UserControl
{
    public CreateFolderView()
    {
        InitializeComponent();
        NameBox = this.FindControl<TextBox>("NameBox");
        PathBox = this.FindControl<TextBox>("PathBox");
        GitBox = this.FindControl<CheckBox>("GitBox");
        ReadMeBox = this.FindControl<CheckBox>("ReadMeBox");
        IgnoreBox = this.FindControl<CheckBox>("IgnoreBox");
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }

    private void OkClick(object? sender, RoutedEventArgs e)
    {
        if(Parent is null)return;
        if(Parent.DataContext is not MainWindowViewModel model)return;
        if (string.IsNullOrEmpty(NameBox.Text) || string.IsNullOrEmpty(PathBox.Text)) return;
        var path = Path.Combine(PathBox.Text, NameBox.Text);
        Directory.CreateDirectory(path);
        if (GitBox.IsChecked != null && (bool)GitBox.IsChecked) Repository.Init(path);
        if (ReadMeBox.IsChecked != null && (bool)ReadMeBox.IsChecked) File.Create(Path.Combine(path, "README.md"));
        if (IgnoreBox.IsChecked != null && (bool)IgnoreBox.IsChecked)File.Create(Path.Combine(path, ".gitignore"));
        model.ToFolderView(path);
    }

    private async void ChooseClick(object? sender, RoutedEventArgs e)
    {
        var dialog = new OpenFolderDialog();
        var result = await dialog.ShowAsync(new Window());
        if(string.IsNullOrEmpty(result))return;
        PathBox.Text = result;
    }
}